<template>
    <div class="login-log-container">
        <!-- 表单搜索项 -->
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="领料单编码">
                        <el-input v-model="params.issueCode" placeholder="请输入领料单编号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="领料单名称">
                        <el-input v-model="params.issueName" placeholder="请输入领料单名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="仓库名称">
                        <el-input v-model="params.warehouseName" placeholder="请输入仓库名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                </el-row>
                <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="领料日期">
                        <el-date-picker v-model="params.issueDate" type="date" placeholder="领料日期"
                            style="width: 100%;"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="状态">
                        <el-select v-model="params.status" placeholder="请选择单据状态" clearable
                        @change="handleStatusChange" style="width:195px">
                        <el-option label="草稿" value="PREPARE" />
                        <el-option label="已确认" value="CONFIRMED" />
                        <el-option label="审批中" value="APPROVING" />
                        <el-option label="已审批" value="APPROVED" />
                        <el-option label="已完成" value="FINISHED" />
                        <el-option label="已拒绝" value="REFUSE" />
                        <el-option label="已生成生产订单" value="WORK_ORDER_FINISHED" />
                    </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" plain :icon="Refresh" @click="handleReset">重置</el-button>
                </el-col>
            </el-row>
        </el-form>

        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <el-button type="primary" :icon="Plus" plain @click="openInsert">新增</el-button>
                <el-button type="danger" plain :disabled="!selectedRows.length" :icon="Delete"
                    @click="handleDelete">删除</el-button>
                <el-button type="danger" plain @click="clearAll">清空</el-button>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle @click="toggleSearchVisibility"></el-button>
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle @click="handleReset"></el-button>
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-row>
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40"></el-table-column>
                <el-table-column prop="issueCode" label="领料单编码" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="issueName" label="领料单名称" align="center"></el-table-column>
                <el-table-column prop="workorderCode" label="生产工单" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="clientCode" label="客户编码" align="center"></el-table-column>
                <el-table-column prop="clientName" label="客户名称" align="center"></el-table-column>
                <el-table-column prop="issueDate" label="领料日期" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" align="center">
                    <template #default="scope">
                        <span>{{ getStatusLabel(scope.row.status) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300px" align="center">
                    <template #default="scope">
                            <!-- 使用 v-if 判断 status 是否不等于 'COMPLETED' -->
                        <div v-if="scope.row.status !== 'COMPLETED'">
                            <el-button type="primary" @click="handleEdit(scope.row)" text size="small" :icon="EditPen">修改</el-button>
                            <el-button type="success" @click="handleExecute(scope.row)" text size="small" :icon="Check">执行领料</el-button>
                            <el-button type="danger" @click="handleSingleDelete(scope.row)" text size="small" :icon="Delete">删除</el-button>
                        </div>
                            <!-- 如果需要显示其他内容（如提示信息）当 status 为 COMPLETED 时，可以在这里添加 -->
                        <span v-else>该记录已完成，无法进行操作。</span>
                    </template>
                    </el-table-column>
                </el-table>
        </el-row>

        <!-- 分页组件 -->
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                        :page-sizes="pageSizes" layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>
        
        <AddDialog :addDialog="dialogFormVisible" @close-dialog="colseDialog"/>

        <UpdateDialog :updateDialog="dialogFormVisibleUpdate" :updateFrom="updateFrom" @close-dialog="colseDialog"/>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {insertmaterialManagement} from '@/apis/xms/index'
import {findproductionPicking,deletePicking,updatWmIssueLineShuangliang,findWmIssueLine,updatePicking} from '@/apis/zs/index';
import { Search, Refresh, Delete, Plus, EditPen, Check } from '@element-plus/icons-vue';
import AddDialog from '@/components/ProductionPicking/AddDialog.vue';
import UpdateDialog from '@/components/ProductionPicking/UpdateDialog.vue';

const dialogFormVisible = ref(false);// 新增弹窗
const dialogFormVisibleUpdate = ref(false);// 修改弹窗

const handleStatusChange = (value) => {
    params.status = value
}

const getStatusLabel = (status) => {
    if (status === 'PREPARE') return '草稿';
    if (status === 'COMPLETED') return '已完成';
    return '未知状态';
};
// 响应式变量
const tableData = ref([]);
const pageResult = ref({});
const selectedRows = ref([]); // 选中行
const params = reactive({
    currentPage: 1,
    pageSize: 10,
    issueCode: '',
    issueName: '',
    warehouseName: '',
    issueDate: '',
    status: ''
});

// 分页大小
const pageSizes = [2, 5, 10, 20];

// 页面加载时获取数据
onMounted( () => {
    loadData();
});

// 获取数据函数
const loadData = async () => {
    await findproductionPicking(params).then(res =>{
        pageResult.value = res;
        tableData.value = pageResult.value.records;
    });
};

// 处理搜索
const handleSearch = async () => {
     loadData();
};

// 重置搜索参数
const handleReset = async () => {
    Object.assign(params, {
        currentPage: 1,
        pageSize: 10,
        issueCode: '',
        issueName: '',
        warehouseName: '',
        issueDate: '',
        status: ''
    });
    await loadData();
};

// 分页大小变化
const handleSizeChange = async (size) => {
    params.pageSize = size;
    await loadData();
};

// 当前页变化
const handleCurrentChange = async (currentPage) => {
    params.currentPage = currentPage;
    await loadData();
};

// 选中行变化
const handleSelectionChange = (val) => {
    selectedRows.value = val; // 更新选中行
};

const openInsert = () => {
    dialogFormVisible.value = true;
};



let updateFrom = reactive({});// 修改弹窗表单数据
const handleEdit = (row) => {// 打开修改弹窗
    dialogFormVisibleUpdate.value = true;// 打开修改弹窗
    updateFrom = row;// 赋值修改弹窗表单数据
    // console.log(updateFrom);
};



// 删除选中行
const handleDelete = () => {
    if (!selectedRows.value.length) {
        ElMessage.warning('请先选择要删除的项');
        return;
    }
    ElMessageBox.confirm('是否确认删除这些数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteSelectedRows();
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};

const deleteSelectedRows = async () => {
    const selectedIds = selectedRows.value.map(row => row.issueId); // 假设使用 issueCode 作为唯一标识
    try {
        await deletePicking(selectedIds);
        ElMessage({ type: 'success', message: '删除成功' });
        await loadData();
    } catch (error) {
        ElMessage({ type: 'error', message: '删除失败：' + error.message });
    }
};

// 清空所有选择并重置参数
const clearAll = () => {
    Object.assign(params, {
        currentPage: 1,
        pageSize: 10,
        issueCode: '',
        issueName: '',
        warehouseName: '',
        issueDate: '',
        status: ''
    });
    selectedRows.value = []; // 清空选中的行
};

// 控制搜索框的显示与隐藏
const toggleSearchVisibility = () => {
    const searchForm = document.querySelector('.login-log-container > .el-form');
    if (searchForm) {
        searchForm.style.display = searchForm.style.display === 'none' ? 'block' : 'none';
    }
};

const colseDialog =async () => { // 关闭弹窗
    dialogFormVisible.value = false;    // 关闭新增弹窗
    dialogFormVisibleUpdate.value = false;  // 关闭修改弹窗
    await loadData(); // 刷新数据
};




const handleExecute = (row) => {
    // 显示确认提示框
     // 继续执行其他逻辑，比如确认出库
     ElMessageBox.confirm(`确认执行出库？`, '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(async () => { // 执行出库逻辑
        const issueId = row.issueId; // 获取领料单的 ID
    // 查询物料信息
    try {
        pageResultS.value = await findWmIssueLine({ id: issueId }); // 假设根据领料单 ID 查询物料信息
        materialDetails.value = pageResultS.value.records; // 赋值物料信息
        console.log('获取到的物料信息:', materialDetails.value); // 输出物料信息以供调试
        if (!materialDetails.value || materialDetails.value.length === 0) {
            ElMessage.error('请指定领出的物资');
            return;
        }
            console.log('执行出库逻辑',materialDetails.value);
            materialDetails.value.forEach(element => {
                let sa = {
                    lineId: element.lineId,
                    // materialProductId: element.materialStockId,
                    materialProductCode: element.materialProductCode,
                    materialProductName: element.productName,
                    specificationAndModel: element.specificationAndModel,
                    inventoryQuantity: element.quantityIssued,
                    warehouseCode:element.warehouseCode,
                    warehouseAreaCode: element.areaCode,
                    warehouseLocationCode: element.locationCode,
                    inboundBatchNumber: element.batchCode,
                    unitName:element.unitOfMeasure,
                    productionOrder : element.wmIssueHeader.workorderCode,
                    indate : element.wmIssueHeader.issueDate,
                };
                console.log('出库请求参数:', sa); // 输出出库请求参数以供调试
                updatWmIssueLineShuangliang(sa).then(async res => {// 调用出库的 API
                    if (res == "成功") {
                        ElMessage.success('出库成功');
                        const updateZ = {
                            issueId,
                            status:"COMPLETED",
                        }
                        await updatePicking(updateZ);
                        await loadData(); // 刷新数据
                    } else {
                        ElMessage.error('出库失败');
                    }   
                }); 
            });
        } catch (error) {
            ElMessage.error('获取物料信息失败：' + error.message);
        }
    }).catch(() => {
        ElMessage.info('操作已取消');
    });
};
const pageResultS = ref({});//分页数据
const materialDetails = ref([]) // 物料信息
// 执行领料的逻辑
const executePicking = async (row) => {
   
};




</script>

<style scoped>
.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}
</style>
